package com.itfreer.file.remote;

import com.itfreer.file.FileSegmentInfo;
import com.itfreer.utils.common.JSONUtils;
import com.itfreer.utils.config.ConfigManager;
import com.itfreer.utils.http.HttpUtils;

import java.util.HashMap;

/**
 * 定义文件服务
 */
public class FileService {

    /**
     * 单一实例
     */
    public static final FileService instance = new FileService();

    private FileService(){

    }

    /**
     * 断点续传下载
     */
    public FileSegmentInfo downloadFile(
            String bucketName,
            String objectKey,
            FileSegmentInfo segmentInfo) {
        try {
            HashMap<String, Object> params = new HashMap<>();
            params.put("bucketName", bucketName);
            params.put("objectKey", objectKey);
            params.put("segmentInfo", JSONUtils.toJSONString(segmentInfo));
            String url = ConfigManager.getConfig("HttpUrl").toString();
            url += "/rest/file/objectDownloadService/downloadFile";

            FileSegmentInfo fInfo = HttpUtils.post(url, params, FileSegmentInfo.class);
            return fInfo;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 断点续传上传
     */
    public Boolean uploadFile(
            String bucketName,
            String objectKey,
            FileSegmentInfo segmentInfo) {
        try {
            HashMap<String, Object> params = new HashMap<>();
            params.put("bucketName", bucketName);
            params.put("objectKey", objectKey);
            params.put("part", JSONUtils.toJSONString(segmentInfo));

            String url = ConfigManager.getConfig("HttpUrl").toString();
            url += "/rest/file/objectUploadService/uploadFile";

            Boolean fInfo = HttpUtils.post(url, params, Boolean.class);
            return fInfo;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
